#!/usr/bin/env python
# encoding: utf-8
import numpy as np
from utils.time_utisl import *
from utils.common import *
from feature_set.base_feature import BaseFeature, RequstData


class DevUnBaseV1(BaseFeature):
    def __init__(self):
        super().__init__()
        self.apply_time = None
        self.function_map = {
            'gen_device_feature': self.gen_device_feature
        }

    def load_conf(self):
        """
        load config file
        Returns:

        """
        pass

    def load_request(self, request_data: RequstData):
        """
        get request data and format feature input data
        Args:
            request_data: input detail data

        Returns:
            format device_info
        """
        self.apply_time = datetime.strptime(str(request_data.apply_time), "%Y-%m-%d %H:%M:%S")
        self.data = request_data.data_sources.get('device_info', {})

        if not self.data:
            self.data={}
            self.logger.info('输入数据device_info结点为空')

    def gen_device_feature(self):
        device_feature_dict = {}

        device_data = self.data

        device_brand_dict = {'redmi': 'xiaomi', 'honor': 'huawei', 'poco': 'xiaomi', 'realme': 'oppo'
            , 'bengal': 'oppo', 'infinix': 'chuanyin', 'exynos850': 'samsung'
            , 'tecno': 'chuanyin', 'spes': 'xiaomi', 'lge': 'lg', 'gale': 'xiaomi'
            , 'k69v1_64': 'vivo', 'p410ae': 'motorola', 'k65v1_64_bsp': 'oppo'
            , 'fire': 'xiaomi', 'dandelion': 'xiaomi', 'ginkgo': 'xiaomi'
            , 'a32': 'samsung', 'exynos3830': 'samsung', 'p352': 'motorola'
            , 'a24': 'samsung', 'rm6769': 'oppo', 'a34x': 'samsung', 'exynos7904': 'samsung'
            , 'a22': 'samsung', 'devon': 'motorola'}
        if 'deviceBrand' in device_data and device_data['deviceBrand'] and device_data['deviceBrand'] != '':
            device_brand = device_data['deviceBrand'].lower().strip()
            if device_brand in device_brand_dict.keys():
                device_brand = device_brand_dict[device_brand]
        else:
            device_brand = ''
        device_feature_dict['device_brand'] = device_brand

        if 'version' in device_data and device_data['version'] and device_data['version'] != '':
            version = device_data['version'].lower().strip()
            version_split = version.split('_')
            if len(version_split) == 2:
                device_type = version_split[0]
                device_version = version_split[1]
            elif len(version_split) == 1:
                device_type = ''
                device_version = version_split[0]
            else:
                device_type = ''
                device_version = ''
        else:
            device_type = ''
            device_version = ''
        device_feature_dict['device_type'] = device_type
        device_feature_dict['device_version'] = device_version

        if 'sdCardAvailableSize' in device_data and device_data['sdCardAvailableSize'] and device_data[
            'sdCardAvailableSize'] != '':
            sd_card_available_size = device_data['sdCardAvailableSize'].lower().strip()
            if sd_card_available_size[-1:] == 'g':
                sd_card_available_size = float(sd_card_available_size[:-1])
            elif sd_card_available_size[-2:] == 'gb':
                sd_card_available_size = float(sd_card_available_size[:-2])
            elif sd_card_available_size[-1:] == 'm':
                sd_card_available_size = float(sd_card_available_size[:-1]) / 1024
            elif sd_card_available_size[-2:] == 'mb':
                sd_card_available_size = float(sd_card_available_size[:-2]) / 1024
            elif sd_card_available_size[-4:] == 'byte':
                sd_card_available_size = float(sd_card_available_size[:-4]) / 1024 / 1024 / 1024
            elif sd_card_available_size.isdigit():
                sd_card_available_size = float(sd_card_available_size) / 1024 / 1024 / 1024
            elif is_decimal(sd_card_available_size):
                sd_card_available_size = float(sd_card_available_size)
            else:
                sd_card_available_size = -999
        else:
            sd_card_available_size = -999
        device_feature_dict['sd_card_available_size'] = sd_card_available_size

        if 'screenRateLong' in device_data and device_data['screenRateLong'] and device_data[
            'screenRateLong'] != '':
            screen_rate_long = device_data['screenRateLong'].lower().strip()
            if screen_rate_long.isdigit():
                screen_rate_long = int(screen_rate_long)
            elif is_decimal(screen_rate_long):
                screen_rate_long = float(screen_rate_long)
            else:
                screen_rate_long = -999
        else:
            screen_rate_long = -999
        device_feature_dict['screen_rate_long'] = screen_rate_long

        if 'screenRateWidth' in device_data and device_data['screenRateWidth'] and device_data[
            'screenRateWidth'] != '':
            screen_rate_width = device_data['screenRateWidth'].lower().strip()
            if screen_rate_width.isdigit():
                screen_rate_width = int(screen_rate_width)
            elif is_decimal(screen_rate_width):
                screen_rate_width = float(screen_rate_width)
            else:
                screen_rate_width = -999
        else:
            screen_rate_width = -999
        device_feature_dict['screen_rate_width'] = screen_rate_width

        if 'internetType' in device_data and device_data['internetType'] and device_data['internetType'] != '':
            internet_type = device_data['internetType'].lower().strip()
            internet_type_split = internet_type.split('_')
            if len(internet_type_split) >= 1 and internet_type_split[-1] in ['2g', '3g', '4g', '5g', '6g', 'wifi']:
                internet_type = internet_type_split[-1]
            else:
                internet_type = ''
        else:
            internet_type = ''
        device_feature_dict['internet_type'] = internet_type

        if 'simState' in device_data and device_data['simState'] and device_data['simState'] != '':
            sim_state = device_data['simState'].lower().strip()
            if sim_state.isdigit():
                sim_state = int(sim_state)
            else:
                sim_state = -999
        else:
            sim_state = -999
        device_feature_dict['sim_state'] = sim_state

        if 'screenBrightness' in device_data and device_data['screenBrightness'] is not np.nan and device_data['screenBrightness']:
            screen_brightness = device_data['screenBrightness']
        else:
            screen_brightness = -999
        device_feature_dict['screen_brightness'] = screen_brightness

        if 'mcc' in device_data and device_data['mcc'] and device_data['mcc'] != '':
            mcc = device_data['mcc'].lower().strip()
        else:
            mcc = ''
        device_feature_dict['mcc'] = mcc

        if 'mnc' in device_data and device_data['mnc'] and device_data['mnc'] != '':
            mnc = device_data['mnc'].lower().strip()
        else:
            mnc = ''
        device_feature_dict['mnc'] = mnc

        if 'batteryMax' in device_data and device_data['batteryMax'] is not np.nan and device_data['batteryMax']:
            battery_max = device_data['batteryMax']
        else:
            battery_max = -999
        device_feature_dict['battery_max'] = battery_max

        if 'batteryPower' in device_data and device_data['batteryPower'] is not np.nan and device_data['batteryPower']:
            battery_power = device_data['batteryPower']
        else:
            battery_power = -999
        device_feature_dict['battery_power'] = battery_power

        if 'bootTime' in device_data and device_data['bootTime'] and device_data['bootTime'] != '':
            boot_time = device_data['bootTime'].lower().strip()
        else:
            boot_time = ''
        device_feature_dict['boot_time'] = boot_time

        if 'isRoot' in device_data:
            if device_data['isRoot'] == True:
                is_root = 1
            elif device_data['isRoot'] == False:
                is_root = 0
            else:
                is_root = -999
        else:
            is_root = -999
        device_feature_dict['is_root'] = is_root

        if 'readPrivacyAgreementTime' in device_data and device_data['readPrivacyAgreementTime'] is not np.nan and device_data['readPrivacyAgreementTime']:
            read_privacy_agreement_time = device_data['readPrivacyAgreementTime']
        else:
            read_privacy_agreement_time = -999
        device_feature_dict['read_privacy_agreement_time'] = read_privacy_agreement_time

        if 'readPrivacyAgreementTimes' in device_data and device_data['readPrivacyAgreementTimes'] is not np.nan and device_data['readPrivacyAgreementTimes']:
            read_privacy_agreement_times = device_data['readPrivacyAgreementTimes']
        else:
            read_privacy_agreement_times = -999
        device_feature_dict['read_privacy_agreement_times'] = read_privacy_agreement_times

        if 'backgroundRecoveryTimes' in device_data and device_data['backgroundRecoveryTimes'] is not np.nan and device_data['backgroundRecoveryTimes']:
            background_recovery_times = device_data['backgroundRecoveryTimes']
        else:
            background_recovery_times = -999
        device_feature_dict['background_recovery_times'] = background_recovery_times

        if 'latitudeInfo' in device_data and device_data['latitudeInfo'] and device_data['latitudeInfo'] != '':
            latitude_info = device_data['latitudeInfo'].lower().strip()
            if latitude_info.isdigit():
                latitude_info = int(latitude_info)
            elif is_decimal(latitude_info):
                latitude_info = float(latitude_info)
            else:
                latitude_info=-999
        else:
            latitude_info = -999
        device_feature_dict['latitude_info'] = latitude_info

        if 'longitudeInfo' in device_data and device_data['longitudeInfo'] and device_data['longitudeInfo'] != '':
            longitude_info = device_data['longitudeInfo'].lower().strip()
            if longitude_info.isdigit():
                longitude_info = int(longitude_info)
            elif is_decimal(longitude_info):
                longitude_info = float(longitude_info)
            else:
                longitude_info=-999
        else:
            longitude_info = -999
        device_feature_dict['longitude_info'] = longitude_info

        if 'firstUseAndRequestIntervalTime' in device_data and device_data['firstUseAndRequestIntervalTime'] is not np.nan and device_data['firstUseAndRequestIntervalTime']:
            first_use_and_request_interval_time = device_data['firstUseAndRequestIntervalTime']
        else:
            first_use_and_request_interval_time = -999
        device_feature_dict['first_use_and_request_interval_time'] = first_use_and_request_interval_time

        if 'loginAccountEnterTime' in device_data and device_data['loginAccountEnterTime'] is not np.nan and device_data['loginAccountEnterTime']:
            login_account_enter_time = device_data['loginAccountEnterTime']
        else:
            login_account_enter_time = -999
        device_feature_dict['login_account_enter_time'] = login_account_enter_time

        if 'loanPageStayTime' in device_data and len(str(device_data['loanPageStayTime'])) in [10, 13, 34]:
            loan_page_stay_time = time_trans(device_data['loanPageStayTime'], self.country_code)
            loan_page_stay_time_diff = (self.apply_time - loan_page_stay_time).total_seconds() / (60 * 60)
        else:
            loan_page_stay_time_diff = -999
        device_feature_dict['loan_page_stay_time_diff'] = loan_page_stay_time_diff

        if 'clientType' in device_data and device_data['clientType'] is not np.nan and device_data['clientType']:
            client_type = device_data['clientType']
        else:
            client_type = -999
        device_feature_dict['client_type'] = client_type

        if 'hasGravitySensor' in device_data and device_data['hasGravitySensor'] is not np.nan and device_data['hasGravitySensor']:
            has_gravity_sensor = device_data['hasGravitySensor']
        else:
            has_gravity_sensor = -999
        device_feature_dict['has_gravity_sensor'] = has_gravity_sensor

        if 'hasGyroscopeSensor' in device_data and device_data['hasGyroscopeSensor'] is not np.nan and device_data['hasGyroscopeSensor']:
            has_gyroscope_sensor = device_data['hasGyroscopeSensor']
        else:
            has_gyroscope_sensor = -999
        device_feature_dict['has_gyroscope_sensor'] = has_gyroscope_sensor

        if 'localeIso3Country' in device_data and device_data['localeIso3Country'] and device_data[
            'localeIso3Country'] != '':
            locale_iso_3_country = device_data['localeIso3Country'].lower().strip()
        else:
            locale_iso_3_country = ''
        device_feature_dict['locale_iso_3_country'] = locale_iso_3_country

        if 'physicalSize' in device_data and device_data['physicalSize'] and device_data['physicalSize'] != '':
            physical_size = device_data['physicalSize'].lower().strip()
            if physical_size.isdigit():
                physical_size = int(physical_size)
            elif is_decimal(physical_size):
                physical_size = float(physical_size)
            else:
                physical_size = -999
        else:
            physical_size = -999
        device_feature_dict['physical_size'] = physical_size

        if 'cpuType' in device_data and device_data['cpuType'] and device_data['cpuType'] != '':
            cpu_type = device_data['cpuType'].lower().strip()
        else:
            cpu_type = ''
        device_feature_dict['cpu_type'] = cpu_type

        if 'cpuMax' in device_data and device_data['cpuMax'] and device_data['cpuMax'] != '':
            cpu_max = device_data['cpuMax'].lower().strip()
        else:
            cpu_max = ''
        device_feature_dict['cpu_max'] = cpu_max

        if 'cpuMin' in device_data and device_data['cpuMin'] and device_data['cpuMin'] != '':
            cpu_min = device_data['cpuMin'].lower().strip()
        else:
            cpu_min = ''
        device_feature_dict['cpu_min'] = cpu_min

        if 'cpuCur' in device_data and device_data['cpuCur'] and device_data['cpuCur'] != '':
            cpu_cur = device_data['cpuCur'].lower().strip()
        else:
            cpu_cur = ''
        device_feature_dict['cpu_cur'] = cpu_cur

        if 'manufacturerName' in device_data and device_data['manufacturerName'] and device_data[
            'manufacturerName'] != '':
            manufacturer_name = device_data['manufacturerName'].lower().strip()
        else:
            manufacturer_name = ''
        device_feature_dict['manufacturer_name'] = manufacturer_name

        if 'screenDensity' in device_data and device_data['screenDensity'] and device_data['screenDensity'] != '':
            screen_density = device_data['screenDensity'].lower().strip()
            if screen_density.isdigit():
                screen_density = int(screen_density)
            elif is_decimal(screen_density):
                screen_density = float(screen_density)
            else:
                screen_density = -999
        else:
            screen_density = -999
        device_feature_dict['screen_density'] = screen_density

        if 'screenDensityDpi' in device_data and device_data['screenDensityDpi'] and device_data['screenDensityDpi'] != '':
            screen_density_dpi = device_data['screenDensityDpi'].lower().strip()
            if screen_density_dpi.isdigit():
                screen_density_dpi = int(screen_density_dpi)
            else:
                screen_density_dpi = -999
        else:
            screen_density_dpi = -999
        device_feature_dict['screen_density_dpi'] = screen_density_dpi

        if 'isTablet' in device_data and device_data['isTablet'] is not np.nan and device_data['isTablet']:
            is_tablet = device_data['isTablet']
        else:
            is_tablet = -999
        device_feature_dict['is_tablet'] = is_tablet

        if 'securityPatch' in device_data and device_data['securityPatch'] and device_data['securityPatch'] != '':
            security_patch = device_data['securityPatch'].lower().strip()
        else:
            security_patch = ''
        device_feature_dict['security_patch'] = security_patch

        if 'ramTotalSize' in device_data and device_data['ramTotalSize'] and device_data['ramTotalSize'] != '' and device_data['ramTotalSize'] is not np.nan:
            ram_total_size = str(device_data['ramTotalSize']).lower().strip()
            if ram_total_size.isdigit():
                ram_total_size = float(ram_total_size) / 1024 / 1024 / 1024
            elif is_decimal(ram_total_size):
                ram_total_size = float(ram_total_size)
            else:
                ram_total_size = -999
        else:
            ram_total_size = -999
        device_feature_dict['ram_total_size'] = ram_total_size

        if 'ramUsableSize' in device_data and device_data['ramUsableSize'] and device_data['ramUsableSize'] != '' and device_data['ramUsableSize'] is not np.nan:
            ram_usable_size = str(device_data['ramUsableSize']).lower().strip()
            if ram_usable_size.isdigit():
                ram_usable_size = float(ram_usable_size) / 1024 / 1024 / 1024
            elif is_decimal(ram_usable_size):
                ram_usable_size = float(ram_usable_size)
            else:
                ram_usable_size = -999
        else:
            ram_usable_size = -999
        device_feature_dict['ram_usable_size'] = ram_usable_size

        if 'keyboard' in device_data and device_data['keyboard'] is not np.nan and device_data['keyboard']:
            keyboard = device_data['keyboard']
        else:
            keyboard = -999
        device_feature_dict['keyboard'] = keyboard

        if 'lastBootTime' in device_data and len(str(device_data['lastBootTime'])) in [10, 13, 34]:
            last_boot_time = time_trans(device_data['lastBootTime'], self.country_code)
            last_boot_time_diff = (self.apply_time - last_boot_time).total_seconds() / (60 * 60)
        else:
            last_boot_time_diff = -999
        device_feature_dict['last_boot_time_diff'] = last_boot_time_diff

        if 'isUsingVpn' in device_data and device_data['isUsingVpn'] is not np.nan and device_data['isUsingVpn']:
            is_using_vpn = device_data['isUsingVpn']
        else:
            is_using_vpn = -999
        device_feature_dict['is_using_vpn'] = is_using_vpn

        if 'isUsingProxyPort' in device_data and device_data['isUsingProxyPort'] is not np.nan and device_data['isUsingProxyPort']:
            is_using_proxy_port = device_data['isUsingProxyPort']
        else:
            is_using_proxy_port = -999
        device_feature_dict['is_using_proxy_port'] = is_using_proxy_port

        if 'isUsbDebug' in device_data and device_data['isUsbDebug'] is not np.nan and device_data['isUsbDebug']:
            is_usb_debug = device_data['isUsbDebug']
        else:
            is_usb_debug = -999
        device_feature_dict['is_usb_debug'] = is_usb_debug

        if 'isMockLocation' in device_data and device_data['isMockLocation'] is not np.nan and device_data['isMockLocation']:
            is_mock_location = device_data['isMockLocation']
        else:
            is_mock_location = -999
        device_feature_dict['is_mock_location'] = is_mock_location

        if 'ringerMode' in device_data and device_data['ringerMode'] is not np.nan and device_data['ringerMode']:
            ringer_mode = device_data['ringerMode']
        else:
            ringer_mode = -999
        device_feature_dict['ringer_mode'] = ringer_mode

        if 'isAirplaneMode' in device_data and device_data['isAirplaneMode'] is not np.nan and device_data['isAirplaneMode']:
            is_airplane_mode = device_data['isAirplaneMode']
        else:
            is_airplane_mode = -999
        device_feature_dict['is_airplane_mode'] = is_airplane_mode

        if 'isCharging' in device_data and device_data['isCharging'] is not np.nan and device_data['isCharging']:
            is_charging = device_data['isCharging']
        else:
            is_charging = -999
        device_feature_dict['is_charging'] = is_charging

        if 'chargeType' in device_data and device_data['chargeType'] is not np.nan and device_data['chargeType']:
            charge_type = device_data['chargeType']
        else:
            charge_type = -999
        device_feature_dict['charge_type'] = charge_type

        if 'batteryHealth' in device_data and device_data['batteryHealth'] is not np.nan and device_data['batteryHealth']:
            battery_health = device_data['batteryHealth']
        else:
            battery_health = -999
        device_feature_dict['battery_health'] = battery_health

        if 'batteryTemperature' in device_data and device_data['batteryTemperature'] and device_data['batteryTemperature'] != '' and device_data['batteryTemperature'] is not np.nan:
            battery_temperature = str(device_data['batteryTemperature']).lower().strip()
            if battery_temperature.isdigit():
                battery_temperature = int(battery_temperature)
            elif is_decimal(battery_temperature):
                battery_temperature = float(battery_temperature)
            else:
                battery_temperature = -999
        else:
            battery_temperature = -999
        device_feature_dict['battery_temperature'] = battery_temperature

        return device_feature_dict
